package com.ff.xyh.service.message.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ff.xyh.common.entity.message.RoomMessage;
import com.ff.xyh.common.entity.result.ResultObject;
import com.ff.xyh.common.qo.message.RoomMessageQuery;
import com.ff.xyh.service.message.mapper.RoomMessageMapper;
import com.ff.xyh.service.message.service.RoomMessageService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 群聊消息表 服务实现类
 * </p>
 *
 * @author ff
 * @since 2022-10-26
 */
@Service
public class RoomMessageServiceImpl extends ServiceImpl<RoomMessageMapper, RoomMessage> implements RoomMessageService {

    @Override
    public ResultObject getRoomMessageCondition(RoomMessageQuery roomMessageQuery) {


        Page<RoomMessage> page = new Page<>(roomMessageQuery.getCurrentPage(), roomMessageQuery.getPageSize());
        List<RoomMessage> resultList = new ArrayList<>();
        QueryWrapper<RoomMessage> wrapper = new QueryWrapper<>();

        // 如果通过id查询 那就只需要查询id 然后直接封装返回
        if (!StringUtils.isEmpty(roomMessageQuery.getId())) {
            RoomMessage getById = this.getById(roomMessageQuery.getId());
            if (getById != null)
                resultList.add(getById);
            return ResultObject.ok().putList(resultList, resultList.size());
        }


        if (roomMessageQuery.getGmtAfter() != null) {
            wrapper.ge("gmt_created", roomMessageQuery.getGmtAfter());
        }
        if (roomMessageQuery.getGmtBefore() != null) {
            wrapper.le("gmt_created", roomMessageQuery.getGmtBefore());
        }
        // 按创建时间排序意味着要最新
        if (roomMessageQuery.getOrderByCreatedTime() != null && roomMessageQuery.getOrderByCreatedTime()) {
            // 降序
            wrapper.orderByDesc("gmt_created");
        } else {
            wrapper.orderByAsc("gmt_created");
        }
        // 屏蔽被举报超过10的
        if (roomMessageQuery.getIgnoreComplained()==null || !roomMessageQuery.getIgnoreComplained()) {
            wrapper.le("complaint_number", 10);
        }

        if (!StringUtils.isEmpty(roomMessageQuery.getRoomId())) {
            wrapper.eq("room_id", roomMessageQuery.getRoomId());
        }
        if (!StringUtils.isEmpty(roomMessageQuery.getUserId())) {
            wrapper.eq("user_id", roomMessageQuery.getUserId());
        }

        IPage<RoomMessage> resultPage = this.page(page, wrapper);

        return ResultObject.ok().putList(resultPage.getRecords(), resultPage.getTotal());

    }
}
